﻿Imports System
Imports System.Linq
Imports System.IO
Imports System.IO.IsolatedStorage
Imports System.Collections.Generic
Imports Microsoft.LightSwitch
Imports Microsoft.LightSwitch.Framework.Client
Imports Microsoft.LightSwitch.Presentation
Imports Microsoft.LightSwitch.Presentation.Extensions
Imports System.Windows
Imports Microsoft.LightSwitch.Threading

Imports System.Windows.Controls
Imports System.Windows.Browser
Imports System.Windows.Threading


Namespace LightSwitchApplication

    Public Class LocationsListDetail

        Private _uploadUrl As Uri
        Public Property UploadUrl As Uri
            Get
                Return _uploadUrl
            End Get
            Set(value As Uri)
                _uploadUrl = value
            End Set
        End Property

        Private _currentUri
        Public Property CurrentURI As Uri
            Get
                Return _currentUri
            End Get
            Set(value As Uri)
                _currentUri = value
            End Set
        End Property


        Dim imageUploadFrom As String

        Function checkForCityStateZip() As Boolean
            If Me.Locations.SelectedItem.City = String.Empty Or
                Me.Locations.SelectedItem.State = String.Empty Or
                Me.Locations.SelectedItem.Zip = String.Empty Then
                Return False
            End If
            Return True
        End Function

        Private Sub UploadImageMethod_Execute()
            ' Write your code here.
            If checkForCityStateZip() Then
                imageUploadFrom = "coupon"
                ' To invoke our own dialog, we have to do this inside of the "Main" Dispatcher
                ' And, since this is a web application, we can't directly invoke the Silverlight OpenFileDialog
                ' class, we have to first invoke our own Silverlight custom control (i.e. SelectFileWindow)
                ' and that control will be able to invoke the OpenFileDialog class (via the Browse button)

                Microsoft.LightSwitch.Threading.Dispatchers.Main.BeginInvoke(
                        Sub()
                        Dim selectFileWindow As New SelectFileWindow()
                        AddHandler selectFileWindow.Closed, AddressOf selectFileWindow_Closed
                        selectFileWindow.Show()
                    End Sub)


                '           Dispatcher.Main()
                '           Dim selectFileWindow As New SelectFileWindow()
                '           selectFileWindow.Closed += New EventHandler(selectFileWindow_Closed)
                '           selectFileWindow.Show()
                'End Function)
            Else
                Me.DataWorkspace.ApplicationData.SaveChanges() 'MessageBox.Show("Please enter data for Location City, State and Zipcode before uploading images.")
            End If

        End Sub

        Private Sub selectFileWindow_Closed(ByVal sender As Object, ByVal e As EventArgs)
            Dim selectFileWindow As SelectFileWindow = CType(sender, SelectFileWindow)
            If ((selectFileWindow.DialogResult = True) _
              AndAlso (Not (selectFileWindow.FileInfoFile) Is Nothing)) Then

                Microsoft.LightSwitch.Threading.Dispatchers.Main.BeginInvoke(
                    Sub()
                        UploadFile(selectFileWindow.FileInfoFile)
                    End Sub)


            End If
        End Sub



        Private Sub UploadFile(ByVal SelectedFile As FileInfo)
            ' If there is a file upload it
            If (Not (SelectedFile) Is Nothing) Then
                'SelectedFile.Name.r = "test.jpg"
                ' Get the upload URL
                CurrentURI = GetBaseAddress()
                Dim strURLWithSelectedFolder As String = String.Format("{0}{1}", CurrentURI, "FileUpload.ashx")
                Dim uri As Uri = New Uri(strURLWithSelectedFolder, UriKind.Absolute)
                UploadUrl = uri
                ' Create an FileUpload object
                Dim upload As SimpleMVVMFileUpload.FileUpload = New SimpleMVVMFileUpload.FileUpload(Me.DataWorkspace.Details.Dispatcher, UploadUrl, SelectedFile)
                upload.ChunkSize = 4194304
                ' Wire up handles for status changed and upload percentage
                ' These will be updating the properties that the ViewModel exposes
                AddHandler upload.StatusChanged, AddressOf Me.upload_StatusChanged
                'AddHandler upload.UploadProgressChanged, AddressOf Me.upload_UploadProgressChanged
                AddHandler upload.UploadProgressChanged, New SimpleMVVMFileUpload.ProgressChangedEvent(AddressOf upload_UploadProgressChanged)

                Dim fileNameforSEO As String = Split(SelectedFile.Name, SelectedFile.Extension)(0) & "-" & Me.Locations.SelectedItem.City & "-" & Me.Locations.SelectedItem.State & "-" & Me.Locations.SelectedItem.Zip & SelectedFile.Extension

                ' Start the Upload
                If imageUploadFrom = "mainimage" Then

                    upload.Upload(Me.Locations.SelectedItem.Customer.UserName & "/" & Me.Locations.SelectedItem.DomainName, 410, 310, imageUploadFrom, fileNameforSEO)
                Else
                    upload.Upload(Me.Locations.SelectedItem.Customer.UserName & "/" & Me.Locations.SelectedItem.DomainName, 150, 150, imageUploadFrom, fileNameforSEO)
                End If

            End If
        End Sub




        Private Sub upload_StatusChanged(ByVal sender As Object, ByVal e As EventArgs)
            Dim fu As SimpleMVVMFileUpload.FileUpload = CType(sender, SimpleMVVMFileUpload.FileUpload)
            ' Is upload complete?
            If (fu.Status = SimpleMVVMFileUpload.FileUploadStatus.Complete) Then
                If imageUploadFrom = "images" Then
                    ImagesCollection.SelectedItem.ImageLocation = CurrentURI.ToString & "files/" & Locations.SelectedItem.Customer.UserName & "/" & Me.Locations.SelectedItem.DomainName & "/images/" & fu.fileNameforSEO.ToString
                ElseIf imageUploadFrom = "coupon" Then
                    Coupon1.SelectedItem.ImageLocation = CurrentURI.ToString & "files/" & Locations.SelectedItem.Customer.UserName & "/" & Me.Locations.SelectedItem.DomainName & "/coupon/" & fu.fileNameforSEO.ToString
                ElseIf imageUploadFrom = "mainimage" Then
                    Locations.SelectedItem.ImageLocation = CurrentURI.ToString & "files/" & Locations.SelectedItem.Customer.UserName & "/" & Me.Locations.SelectedItem.DomainName & "/mainimage/" & fu.fileNameforSEO.ToString
                End If


                'Dim fstream = New FileStream(fu.File.ToString, FileMode.Open, FileAccess.Read, FileShare.Read)


                'Coupon1.SelectedItem.Image = GetStreamAsByteArray(fstream)
            End If
        End Sub


        Private Shared Function GetBaseAddress() As Uri
            ' Get the web address of the .xap that launched this application
            Dim strBaseWebAddress As String = System.Windows.Browser.HtmlPage.Document.DocumentUri.AbsoluteUri
            ' Find the position of the ClientBin directory        
            Dim PositionOfClientBin As Integer = System.Windows.Browser.HtmlPage.Document.DocumentUri.AbsoluteUri.ToLower.IndexOf("/default")
            If (PositionOfClientBin > -1) Then
                ' Strip off everything after the ClientBin directory         
                strBaseWebAddress = Microsoft.VisualBasic.Strings.Left(strBaseWebAddress, PositionOfClientBin)
            Else
                strBaseWebAddress = (strBaseWebAddress + "\")
            End If
            ' Create a URI
            Dim UriWebService As Uri = New Uri(String.Format("{0}", strBaseWebAddress))
            ' Return the base address       


            Return UriWebService
        End Function

        Private Sub upload_UploadProgressChanged(sender As Object, args As SimpleMVVMFileUpload.UploadProgressChangedEventArgs)

        End Sub


        Private Function GetStreamAsByteArray(ByVal stream As System.IO.Stream) As Byte()
            If stream IsNot Nothing Then
                Dim streamLength As Integer = Convert.ToInt32(stream.Length)
                Dim fileData(streamLength - 1) As Byte
                stream.Read(fileData, 0, streamLength)
                stream.Close()
                Return fileData
            Else
                Return Nothing
            End If
        End Function


        Private Sub UploadImagesMethod_Execute()
            If checkForCityStateZip() Then
                ' Write your code here.
                imageUploadFrom = "images"
                Microsoft.LightSwitch.Threading.Dispatchers.Main.BeginInvoke(
                   Sub()
                   Dim selectFileWindow As New SelectFileWindow()
                   AddHandler selectFileWindow.Closed, AddressOf selectFileWindow_Closed
                   selectFileWindow.Show()
               End Sub)
            Else
                Me.DataWorkspace.ApplicationData.SaveChanges() 'MessageBox.Show("Please enter data for Location City, State and Zipcode before uploading images.")
            End If
        End Sub

        Private Sub UploadMainImageMethod_Execute()
            If checkForCityStateZip() Then
            
            ' Write your code here.
            imageUploadFrom = "mainimage"
                Microsoft.LightSwitch.Threading.Dispatchers.Main.BeginInvoke(
                   Sub()
                   Dim selectFileWindow As New SelectFileWindow()
                   AddHandler selectFileWindow.Closed, AddressOf selectFileWindow_Closed
                   selectFileWindow.Show()
               End Sub)
            Else
                Me.DataWorkspace.ApplicationData.SaveChanges() 'MessageBox.Show("Please enter data for Location City, State and Zipcode before uploading images.")
            End If
        End Sub

        Private Sub LocationsListDetail_InitializeDataWorkspace(saveChangesTo As System.Collections.Generic.List(Of Microsoft.LightSwitch.IDataService))
            ' Write your code here.
            'If Me.Application.User.HasPermission("Administrator") Then
            '    prpUserName = prpUserName
            'Else
            '    prpUserName = Me.Application.User.Name
            'End If

        End Sub


    End Class

End Namespace
